from apscheduler.schedulers.background import BackgroundScheduler
from agent import *


def get_logs_path(paths, rule):
    """
    获取日志路径
    :param paths: 日志路径
    :param rule: 日志路径规则
    :return: 日志路径
    """
    # 如果日志路径不为空 则使用日志路径 否则使用日志规则解析
    if not len(paths) == 0:
        return paths
    else:
        strategy = LogPathStrategyFactory.get_strategy(next(iter(rule)))
        return strategy.get_logs_path(rule)


if __name__ == '__main__':
    # 读取配置文件
    jsonData = read_config()
    # 获取日志任务
    log_tasks = jsonData['log_tasks']
    scheduler = BackgroundScheduler()
    for log_task in log_tasks:
        # 获取任务名称
        task_name = log_task['name']
        # 获取日志路径
        logs_path = get_logs_path(log_task['log_path'], log_task['log_path_rule'])
        # 获取解析规则
        parse_rule = log_task['parse_rule']
        # 获取cron规则
        cron_rule = log_task['cron_rule']
        # 获取数据库规则
        db_rule = log_task['db_rule']
        rule_type = next(iter(parse_rule))
        parse_strategy = LogsParserFactory.get_parser(rule_type)(parse_rule[rule_type])
        # 添加任务
        scheduler.add_job(parse_strategy.parse_logs, trigger='cron', second=cron_rule[0], minute=cron_rule[1],
                          hour=cron_rule[2],
                          day=cron_rule[3], month=cron_rule[4], year=cron_rule[5],
                          args=(logs_path, parse_rule, task_name, db_rule))
    pid_tasks = jsonData['pid_tasks']
    for pid_task in pid_tasks:
        # 获取任务名称
        task_name = pid_task['name']
        # 获取进程名称
        process_name = pid_task['process_name']
        # 获取cron规则
        cron_rule = pid_task['cron_rule']
        # 获取数据库规则
        db_rule = pid_task['db_rule']
        scheduler.add_job(detect_process, trigger='cron', second=cron_rule[0], minute=cron_rule[1], hour=cron_rule[2],
                          day=cron_rule[3], month=cron_rule[4], year=cron_rule[5],
                          args=(process_name, db_rule))
    # 启动任务
    scheduler.start()
    while True:
        time.sleep(1)
